# -*- coding: utf-8 -*-
import json

from flask import render_template, Blueprint,request,jsonify
from flask_login import login_required
from taobao.mysqls import PyMysql
import pinyin

cursor=PyMysql().pymysql_conn()


main_bp = Blueprint('main', __name__)


@main_bp.route('/')
def index():

    return render_template('main/index.html')


@main_bp.route('/explore')
@login_required
def explore():
    if request.args.get('q'):
        qqq=request.args.get('q')
        tab_name=pinyin.get(qqq, delimiter='_', format='strip')

        return render_template('main/explore.html',q=tab_name)
    else:
        return render_template('main/hello.html')


# ajax请求的路由
@main_bp.route("/zzt",methods=['GET'])
def zzt():

    #根据q查询数据
    if request.method == 'GET':
        formdata = request.args
        tabName = formdata['tabName']

    else:
        tabName='yi_yong_jiu_jing'

    sql = "SELECT location,avg(price) as avg_price FROM "+tabName+" group by location;"  # sql语句

    cursor.execute(sql)  # execute(query, args):执行单条sql语句。
    see = cursor.fetchall()  # 使结果全部可看

    xdays = []
    jsonData = {}
    yvalues = []

    for data in see:
        xdays.append(data[0])
        yvalues.append(data[1])

    # print(xdays)
    # print(yvalues)

    jsonData['xdays'] = xdays
    jsonData['yvalues'] = yvalues

    # print(jsonData)
    # 将json格式转成str，因为如果直接将dict类型的数据写入json会发生报错，因此将数据写入时需要用到该函数。
    j = json.dumps(jsonData, ensure_ascii=False)

    return j


@main_bp.route("/pie",methods=['GET'])
def pie():

    #根据q查询数据
    if request.method == 'GET':
        formdata = request.args
        tabName = formdata['tabName']
    else:
        tabName='yi_yong_jiu_jing'
    sql = "SELECT location,sum(sales) as sa FROM "+tabName+" group by location;"  # sql语句
    cursor.execute(sql)  # execute(query, args):执行单条sql语句。
    see = cursor.fetchall()  # 使结果全部可看

    xdays = []
    jsonData = {}
    yvalues = []
    app=[]

    for data in see:
        seres = {}

        seres['value']=str(data[1])
        seres['name']=data[0]

        xdays.append(data[0])
        yvalues.append(str(data[1]))

        app.append(seres)

    jsonData['xdays'] = xdays
    jsonData['yvalues'] = yvalues

    need={'data':app,'j':jsonData}

    needs=json.dumps(need,ensure_ascii=False)
    return needs


@main_bp.route("/line",methods=['GET'])
def line():

    #根据q查询数据
    if request.method == 'GET':
        formdata = request.args
        tabName = formdata['tabName']

    else:
        tabName='yi_yong_jiu_jing'

    sql = "select location,count(*) as counts from "+tabName+" group by location order by counts desc limit 10;"  # sql语句

    cursor.execute(sql)  # execute(query, args):执行单条sql语句。
    see = cursor.fetchall()  # 使结果全部可看
    # print(sql)
    # print(see)
    # print(cur)
    # 创建json数据
    xdays = []
    jsonData = {}
    yvalues = []

    for data in see:
        xdays.append(data[0])
        yvalues.append(data[1])

    # print(xdays)
    # print(yvalues)

    jsonData['xdays'] = xdays
    jsonData['yvalues'] = yvalues

    # print(jsonData)
    # 将json格式转成str，因为如果直接将dict类型的数据写入json会发生报错，因此将数据写入时需要用到该函数。
    j = json.dumps(jsonData, ensure_ascii=False)


    return j

import collections

@main_bp.route('/cyt',methods=['GET'])
def ciyun():
    if request.method == 'GET':
        formdata = request.args
        tabName = formdata['tabName']

    else:
        tabName='yi_yong_jiu_jing'

    sql = "SELECT title FROM "+tabName+";"  # sql语句

    cursor.execute(sql)  # execute(query, args):执行单条sql语句。
    see = cursor.fetchall()  # 使结果全部可看

    app = []
    for i in see:
        title = i[0]
        for n in title:
            app.append(n)

    c = collections.Counter(app)
    result = []
    for key, value in c.items():
        result.append({
            'name': key,
            'value': value
        })

    datas=result

    return jsonify({"result":datas})